<template>
  <div v-if="visible" class="modal-overlay">
    <div class="card-selector" @click.stop>
      <div class="selector-header">
        <h3>{{ title }}</h3>
        <!-- 实时计数显示 -->
        <div v-if="multiple && isAi" class="card-counter">
          <span class="counter-text">
            已选择: {{ selectedCardsSet.size }} /
            {{ maxSelection === 0 ? '∞' : maxSelection }}
          </span>
          <div v-if="maxSelection > 0" class="progress-bar">
            <div
              class="progress-fill"
              :style="{
                width: `${(selectedCardsSet.size / maxSelection) * 100}%`,
              }"
              :class="{
                'progress-full': selectedCardsSet.size >= maxSelection,
              }"
            ></div>
          </div>
        </div>
      </div>

      <!-- 牌型快速选择按钮 -->
      <!-- <div class="pattern-buttons" v-if="patternShow">
        <button
          v-for="pattern in quickPatterns"
          :key="pattern.type"
          :class="['pattern-btn', { active: selectedPattern === pattern.type }]"
          @click="selectPattern(pattern.type)"
        >
          {{ pattern.name }}
        </button>
      </div> -->

      <!-- 牌型验证显示 -->
      <!-- <div v-if="patternShow" class="pattern-validation">
        <div class="pattern-info">
          <div class="detected-pattern">
            <span class="label">检测到的牌型:</span>
            <span
              class="pattern-name"
              :class="{
                'pattern-match': isPatternMatched,
                'pattern-mismatch': !isPatternMatched && selectedPattern,
              }"
            >
              {{ detectedPattern.name }}
            </span>
          </div>
          <div v-if="selectedPattern" class="selected-pattern">
            <span class="label">选择的牌型:</span>
            <span class="pattern-name">{{
              getPatternName(selectedPattern)
            }}</span>
          </div>
        </div>
        <div
          v-if="selectedPattern && !isPatternMatched"
          class="validation-error"
        >
          ⚠️ 选中的牌与指定牌型不匹配，请重新选择
        </div>
        <div
          v-if="selectedPattern && isPatternMatched"
          class="validation-success"
        >
          ✅ 牌型匹配正确
        </div>
      </div> -->

      <!-- 级牌选择时只显示红心牌 -->
      <div v-if="isLevelCardSelection" class="level-card-selection">
        <div class="suit-section">
          <div class="suit-header">
            <span class="suit-label red">红心 ♥ (级牌选择)</span>
          </div>
          <div class="cards-grid">
            <div class="cards-row">
              <PokerCard
                v-for="card in levelCardOptions"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="medium"
                @click="toggleCard"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 扑克牌选择区域 (非级牌选择时显示) -->
      <div v-if="!isLevelCardSelection" class="cards-area">
        <!-- 黑桃 -->
        <div class="suit-section">
          <div class="suit-header">
            <span class="suit-label">黑桃 ♠</span>
          </div>
          <div class="cards-grid">
            <div class="cards-row">
              <PokerCard
                v-for="card in spadeCards.slice(0, 13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
            <div class="cards-row">
              <PokerCard
                v-for="card in spadeCards.slice(13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
          </div>
        </div>

        <!-- 红桃 -->
        <div class="suit-section">
          <div class="suit-header">
            <span class="suit-label red">红桃 ♥</span>
          </div>
          <div class="cards-grid">
            <div class="cards-row">
              <PokerCard
                v-for="card in heartCards.slice(0, 13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
            <div class="cards-row">
              <PokerCard
                v-for="card in heartCards.slice(13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
          </div>
        </div>

        <!-- 梅花 -->
        <div class="suit-section">
          <div class="suit-header">
            <span class="suit-label">梅花 ♣</span>
          </div>
          <div class="cards-grid">
            <div class="cards-row">
              <PokerCard
                v-for="card in clubCards.slice(0, 13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
            <div class="cards-row">
              <PokerCard
                v-for="card in clubCards.slice(13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
          </div>
        </div>

        <!-- 方块 -->
        <div class="suit-section">
          <div class="suit-header">
            <span class="suit-label red">方块 ♦</span>
          </div>
          <div class="cards-grid">
            <div class="cards-row">
              <PokerCard
                v-for="card in diamondCards.slice(0, 13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
            <div class="cards-row">
              <PokerCard
                v-for="card in diamondCards.slice(13)"
                :key="card.id"
                :card="card"
                :selected="isCardSelected(card)"
                :played="isCardPlayed(card)"
                size="small"
                @click="toggleCard"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 大小王区域 (非级牌选择时显示) -->
      <div v-if="!isLevelCardSelection" class="jokers-section">
        <div class="jokers-header">大小王</div>
        <div class="jokers-grid">
          <PokerCard
            v-for="joker in jokerCards"
            :key="joker.id"
            :card="joker"
            :selected="isCardSelected(joker)"
            :played="isCardPlayed(joker)"
            size="small"
            @click="toggleCard"
          />
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button
          class="btn btn-success"
          :disabled="!canConfirm"
          :class="{ 'btn-disabled': !canConfirm }"
          @click="handleConfirm"
        >
          确认
        </button>
        <button class="btn btn-primary" @click="handleCancel">取消</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Card, CardSuit, CardPattern, CardRank } from '../types/card'
import { generateDoubleDeck, groupCardsBySuit } from '../utils/cardUtils'
import { identifyCardPattern } from '../utils/gameLogic'
import PokerCard from './PokerCard.vue'

interface Props {
  visible: boolean
  multiple?: boolean
  selectedCards?: Card[]
  title?: string
  patternShow?: boolean
  isLevelCardSelection?: boolean // 是否为级牌选择
  isAi?: boolean
  maxSelection?: number // 最大选择数量
  skipValidation?: boolean // 是否跳过牌型验证
  playedCards?: Card[] // 本局已出过的牌
}

interface Emits {
  (e: 'confirm', cards: Card[]): void
  (e: 'cancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  multiple: false,
  selectedCards: () => [],
  title: '级牌选择...',
  patternShow: false,
  isLevelCardSelection: false,
  maxSelection: 0, // 0表示无限制
  skipValidation: false, // 默认不跳过验证
  playedCards: () => [], // 默认空数组
})

const emit = defineEmits<Emits>()

// 响应式数据
const selectedCardsSet = ref(
  new Set(props.selectedCards?.map((card) => card.id) || [])
)
const selectedPattern = ref<CardPattern | null>(null)

// 监听组件显示状态，默认选中"单"牌型
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && props.patternShow && !props.isLevelCardSelection) {
      // 组件显示且启用牌型选择时，默认选中"单"牌型
      selectedPattern.value = CardPattern.SINGLE
    }
  },
  { immediate: true }
)

// 生成两副牌组并按花色分组
const fullDeck = generateDoubleDeck()
const cardsBySuit = groupCardsBySuit(fullDeck)

// 各花色的牌
const spadeCards = computed(() => cardsBySuit[CardSuit.SPADE])
const heartCards = computed(() => cardsBySuit[CardSuit.HEART])
const clubCards = computed(() => cardsBySuit[CardSuit.CLUB])
const diamondCards = computed(() => cardsBySuit[CardSuit.DIAMOND])
const jokerCards = computed(() => [
  ...cardsBySuit[CardSuit.SMALL_JOKER],
  ...cardsBySuit[CardSuit.BIG_JOKER],
])

// 顶部展示的两行黑桃牌 (A到K)
const topRowSpades = computed(() => {
  const spades = cardsBySuit[CardSuit.SPADE]
  // 按面值排序，从A到K
  const sortedSpades = spades
    .filter((card) => card.rank >= CardRank.TWO && card.rank <= CardRank.ACE)
    .sort((a, b) => {
      // A排在最前面
      if (a.rank === CardRank.ACE && b.rank !== CardRank.ACE) return -1
      if (b.rank === CardRank.ACE && a.rank !== CardRank.ACE) return 1
      return a.rank - b.rank
    })
  return sortedSpades.slice(0, 13) // 第一副牌的A到K
})

const bottomRowSpades = computed(() => {
  const spades = cardsBySuit[CardSuit.SPADE]
  const sortedSpades = spades
    .filter((card) => card.rank >= CardRank.TWO && card.rank <= CardRank.ACE)
    .sort((a, b) => {
      if (a.rank === CardRank.ACE && b.rank !== CardRank.ACE) return -1
      if (b.rank === CardRank.ACE && a.rank !== CardRank.ACE) return 1
      return a.rank - b.rank
    })
  return sortedSpades.slice(13, 26) // 第二副牌的A到K
})

// 级牌选择时的红心牌选项 (2到A，包括JQK)
const levelCardOptions = computed(() => {
  const hearts = cardsBySuit[CardSuit.HEART]
  // 只取第一副牌的红心2到A，按顺序排列，排除大小王
  return hearts
    .filter(
      (card) =>
        card.rank >= CardRank.TWO &&
        card.rank <= CardRank.ACE &&
        card.suit === CardSuit.HEART && // 确保是红心，排除大小王
        card.id < 10000 // 只取第一副牌（ID小于10000）
    )
    .sort((a, b) => a.rank - b.rank) // 按2,3,4,5,6,7,8,9,10,J,Q,K,A的顺序排列
})

// 快速牌型选择
const quickPatterns = [
  // { type: CardPattern.PASS, name: '过牌' },
  { type: CardPattern.SINGLE, name: '单' },
  { type: CardPattern.PAIR, name: '对子' },
  { type: CardPattern.TRIPLE, name: '刻子' },
  { type: CardPattern.TRIPLE_WITH_PAIR, name: '三带二' },
  { type: CardPattern.WOOD_BOARD, name: '木板' },
  { type: CardPattern.STEEL_BOARD, name: '钢板' },
  { type: CardPattern.STRAIGHT, name: '顺子' },
  { type: CardPattern.FOUR_BOMB, name: '四炸' },
  { type: CardPattern.FIVE_BOMB, name: '五炸' },
  { type: CardPattern.SAME_SUIT_STRAIGHT, name: '同花顺' },
  { type: CardPattern.SIX_BOMB, name: '六炸' },
  { type: CardPattern.SEVEN_BOMB, name: '七炸' },
  { type: CardPattern.EIGHT_BOMB, name: '八炸' },
  { type: CardPattern.NINE_BOMB, name: '九炸' },
  { type: CardPattern.TEN_BOMB, name: '十炸' },
  { type: CardPattern.KING_BOMB, name: '天王炸' },
]

// 计算属性
const selectedCardsArray = computed(() => {
  return fullDeck.filter((card) => selectedCardsSet.value.has(card.id))
})

// 识别当前选中牌的牌型
const detectedPattern = computed(() => {
  if (selectedCardsArray.value.length === 0) {
    return { type: CardPattern.PASS, name: '未选择' }
  }

  const combination = identifyCardPattern(selectedCardsArray.value)
  const patternName = getPatternName(combination.type)

  return {
    type: combination.type,
    name: patternName,
    power: combination.power,
  }
})

// 检查牌型是否匹配
const isPatternMatched = computed(() => {
  if (!selectedPattern.value) return true // 未选择牌型时不验证
  if (selectedCardsArray.value.length === 0) return false // 未选择牌时不匹配

  return detectedPattern.value.type === selectedPattern.value
})

// 是否可以确认出牌
const canConfirm = computed(() => {
  if (selectedCardsArray.value.length === 0) return false

  // 如果跳过验证，直接允许确认
  if (props.skipValidation) return true

  // AI手牌选择时，只要选择了牌就可以确认，不验证牌型
  if (props.isAi) return true

  // 级牌选择时，只要选择了牌就可以确认
  if (props.isLevelCardSelection) return true

  // 检查识别的牌型是否有效（不能是PASS）
  if (detectedPattern.value.type === CardPattern.PASS) {
    return false
  }

  // 如果启用了牌型选择，验证是否匹配
  if (props.patternShow && selectedPattern.value) {
    return isPatternMatched.value
  }

  return true
})

// 辅助函数
const getPatternName = (pattern: CardPattern): string => {
  const patternNames = {
    [CardPattern.PASS]: '过牌',
    [CardPattern.SINGLE]: '单张',
    [CardPattern.PAIR]: '对子',
    [CardPattern.TRIPLE]: '刻子',
    [CardPattern.TRIPLE_WITH_PAIR]: '三带二',
    [CardPattern.WOOD_BOARD]: '木板',
    [CardPattern.STEEL_BOARD]: '钢板',
    [CardPattern.STRAIGHT]: '顺子',
    [CardPattern.FOUR_BOMB]: '四炸',
    [CardPattern.FIVE_BOMB]: '五炸',
    [CardPattern.SIX_BOMB]: '六炸',
    [CardPattern.SEVEN_BOMB]: '七炸',
    [CardPattern.EIGHT_BOMB]: '八炸',
    [CardPattern.NINE_BOMB]: '九炸',
    [CardPattern.TEN_BOMB]: '十炸',
    [CardPattern.SAME_SUIT_STRAIGHT]: '同花顺',
    [CardPattern.KING_BOMB]: '天王炸',
  }
  return patternNames[pattern] || '未知牌型'
}

// 创建已出牌的ID Set，用于快速查找
const playedCardIdsSet = computed(() => {
  const set = new Set<number>()
  props.playedCards.forEach((card) => {
    // 使用牌的唯一ID
    set.add(card.id)
  })
  return set
})

// 检查牌是否已被出过（通过ID精确匹配）
const isCardPlayed = (card: Card): boolean => {
  return playedCardIdsSet.value.has(card.id)
}

// 方法
const isCardSelected = (card: Card): boolean => {
  return selectedCardsSet.value.has(card.id)
}

const toggleCard = (card: Card) => {
  // 如果牌已被出过，不允许选择
  if (isCardPlayed(card)) {
    return
  }

  if (props.isLevelCardSelection) {
    // 级牌选择时只允许单选
    selectedCardsSet.value.clear()
    selectedCardsSet.value.add(card.id)
  } else if (props.multiple) {
    if (selectedCardsSet.value.has(card.id)) {
      // 取消选择
      selectedCardsSet.value.delete(card.id)
    } else {
      // 检查是否超过最大选择数量
      if (
        props.maxSelection > 0 &&
        selectedCardsSet.value.size >= props.maxSelection
      ) {
        // 已达到最大选择数量，不能再选择
        return
      }
      selectedCardsSet.value.add(card.id)
    }
  } else {
    // 单选模式
    selectedCardsSet.value.clear()
    selectedCardsSet.value.add(card.id)
  }
}

const selectPattern = (pattern: CardPattern) => {
  selectedPattern.value = pattern
  // 选择牌型时清空已选择的牌，让用户重新选择
  selectedCardsSet.value.clear()
}

const handleConfirm = () => {
  if (!canConfirm.value) {
    return
  }
  const cardsToEmit = [...selectedCardsArray.value]

  emit('confirm', cardsToEmit)
}

// 清除选择状态的方法
const clearSelection = () => {
  selectedCardsSet.value.clear()
  selectedPattern.value = null
}

const handleCancel = () => {
  // 重置状态
  selectedCardsSet.value.clear()
  selectedPattern.value = null
  emit('cancel')
}

// 移除背景点击关闭功能
// const handleOverlayClick = () => {
//   handleCancel()
// }
</script>

<style scoped>
.card-selector {
  background: var(--poker-green);
  border: 3px solid #ffd700;
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-lg);
  width: fit-content;
  max-height: 90vh;
  overflow-y: auto;
  color: white;
}

.selector-header {
  text-align: center;
  margin-bottom: var(--spacing-md);
}

.selector-header h3 {
  color: white;
  font-size: 18px;
  margin: 0;
}

/* 实时计数器样式 */
.card-counter {
  margin-top: var(--spacing-sm);
  text-align: center;
}

.counter-text {
  color: #ffd700;
  font-size: 14px;
  font-weight: bold;
  display: block;
  margin-bottom: var(--spacing-xs);
}

.progress-bar {
  width: 200px;
  height: 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  margin: 0 auto;
  overflow: hidden;
  border: 1px solid #666;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4caf50, #8bc34a);
  transition:
    width 0.3s ease,
    background 0.3s ease;
  border-radius: 3px;
}

.progress-fill.progress-full {
  background: linear-gradient(90deg, #ff9800, #ff5722);
}

/* 牌型按钮区域 */
.pattern-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
  margin-bottom: var(--spacing-lg);
  justify-content: center;
}

.pattern-btn {
  padding: 6px 12px;
  border: 1px solid #666;
  border-radius: var(--border-radius);
  background: #444;
  color: white;
  font-size: 12px;
  cursor: pointer;
  transition: var(--transition);
}

/* 悬浮效果已删除 */
hover {
  background: #555;
}

.pattern-btn.active {
  background: var(--btn-primary);
  border-color: var(--btn-primary);
}

/* 顶部展示区域 */
.top-cards-display {
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  border: 2px solid #ffd700;
  border-radius: var(--border-radius);
  background: rgba(0, 0, 0, 0.3);
}

.top-cards-display .cards-row {
  display: flex;
  gap: var(--spacing-xs);
  justify-content: center;
  margin-bottom: var(--spacing-xs);
}

.top-cards-display .cards-row:last-child {
  margin-bottom: 0;
}

/* 扑克牌区域 */
.cards-area {
  margin-bottom: var(--spacing-lg);
}

.suit-section {
  margin-bottom: var(--spacing-md);
  border: 2px solid #666;
  border-radius: var(--border-radius);
  padding: var(--spacing-sm);
  background: rgba(0, 0, 0, 0.2);
}

.suit-header {
  margin-bottom: var(--spacing-sm);
}

.suit-label {
  font-weight: bold;
  font-size: 14px;
  color: white;
}

.suit-label.red {
  color: var(--suit-red);
}

.cards-grid {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.cards-row {
  display: flex;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

/* 大小王区域 */
.jokers-section {
  margin-bottom: var(--spacing-lg);
  border: 2px solid #666;
  border-radius: var(--border-radius);
  padding: var(--spacing-sm);
  background: rgba(0, 0, 0, 0.2);
}

.jokers-header {
  font-weight: bold;
  font-size: 14px;
  color: white;
  margin-bottom: var(--spacing-sm);
}

.jokers-grid {
  display: flex;
  gap: var(--spacing-sm);
  justify-content: center;
}

/* 牌型验证显示 */
.pattern-validation {
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  border: 2px solid #666;
  border-radius: var(--border-radius);
  background: rgba(0, 0, 0, 0.3);
}

.pattern-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.detected-pattern,
.selected-pattern {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.label {
  color: #ccc;
  font-size: 14px;
  min-width: 100px;
}

.pattern-name {
  font-weight: bold;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.1);
}

.pattern-name.pattern-match {
  color: #4caf50;
  background: rgba(76, 175, 80, 0.2);
  border: 1px solid #4caf50;
}

.pattern-name.pattern-mismatch {
  color: #f44336;
  background: rgba(244, 67, 54, 0.2);
  border: 1px solid #f44336;
}

.validation-error {
  color: #f44336;
  font-size: 13px;
  text-align: center;
  padding: var(--spacing-xs);
  background: rgba(244, 67, 54, 0.1);
  border: 1px solid #f44336;
  border-radius: 4px;
}

.validation-success {
  color: #4caf50;
  font-size: 13px;
  text-align: center;
  padding: var(--spacing-xs);
  background: rgba(76, 175, 80, 0.1);
  border: 1px solid #4caf50;
  border-radius: 4px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: var(--spacing-md);
  justify-content: center;
}

.action-buttons .btn {
  min-width: 80px;
  padding: var(--spacing-sm) var(--spacing-lg);
}

.btn-disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #666 !important;
  border-color: #666 !important;
}

.btn-disabled:hover {
  background: #666 !important;
  transform: none !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-selector {
    max-width: 95vw;
    padding: var(--spacing-md);
  }

  .pattern-buttons {
    gap: 4px;
  }

  .pattern-btn {
    padding: 4px 8px;
    font-size: 11px;
  }

  .cards-row {
    gap: 2px;
  }

  .jokers-grid {
    gap: var(--spacing-xs);
  }
}
</style>
